package com.whl.sm.controller.system;


import com.whl.sm.common.result.Result;
import com.whl.sm.dto.TreeDto;
import com.whl.sm.model.system.SysMenu;
import com.whl.sm.service.system.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhaolun
 * @since 2021-09-10
 */
@RestController
@RequestMapping("/sys-menu")
public class SysMenuController  {

    @Autowired
    SysMenuService sysMenuService;

    @RequestMapping("/tree")
    public Result meunTree(){
        return Result.ok(sysMenuService.getMenuTree());
    }

    @RequestMapping("/info/{id}")
    public Result meunInfo(@PathVariable("id") String id){
        return Result.ok(sysMenuService.getById(id));
    }

    @RequestMapping("/permTree")
    public Result permTree(){
        Map<String,Object> result = new HashMap<>();
        result.put("permTree",convertToPerm(sysMenuService.getMenuTree()));
        return Result.ok(result);
    }


    @RequestMapping("/info/update")
    public Result updateMenu(@RequestBody SysMenu sysMenu){
        sysMenuService.update(sysMenu);
        return Result.ok();
    }

    @RequestMapping("/delete/{id}")
    public Result delete(@PathVariable("id") String id){
        sysMenuService.removeById(id);
        return Result.ok();
    }





    //用户菜单权限分配树转换
    private List<TreeDto> convertToPerm(List<SysMenu> menus) {
        List<TreeDto> permMenuDtos = new ArrayList<>();
        menus.forEach(m -> {
            TreeDto dto = new TreeDto();
            dto.setId(m.getId());
            dto.setLabel(m.getMenuName());
            if (m.getChildren().size() > 0) {
                dto.setChildren(convertToPerm(m.getChildren()));
            }
            permMenuDtos.add(dto);
        });
        return permMenuDtos;
    }
}
